package com.lys.eduservice.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lys.commonutils.R;
import com.lys.eduservice.client.VodClient;
import com.lys.eduservice.entity.EduVideo;
import com.lys.eduservice.service.EduVideoService;
import com.lys.servicebase.exceptionhandler.GuliException;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * <p>
 * 课程视频 前端控制器
 * </p>
 *
 * @author lys
 * @since 2022-06-29
 */
@Api(tags = "小节管理")
@RestController
@RequestMapping("/eduservice/eduvideo")
public class EduVideoController {
    @Autowired
    private EduVideoService eduVideoService;
    @Autowired
    private VodClient vodClient;

    //添加小节信息
    @PostMapping("/addVideo")
    @ApiOperation(value = "添加小节接口")
    public R addVideo(@RequestBody EduVideo eduVideo){
        boolean flag = eduVideoService.save(eduVideo);
        if (flag){
            return R.ok();
        }else {
            return R.error();
        }
    }

    //根据VideoId查询小节信息
    @GetMapping("/findVideoById/{videoId}")
    @ApiOperation(value = "根据chapterId查询小节接口")
    public R findVideoById(@PathVariable String videoId){
        LambdaQueryWrapper<EduVideo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(EduVideo::getId,videoId);
        EduVideo eduVideo = eduVideoService.getOne(queryWrapper);
        return R.ok().data("eduVideo",eduVideo);
    }

    //修改小节信息
    @PostMapping("/updateVideoById")
    @ApiOperation(value = "修改小节信息接口")
    public R updateVideoById(@RequestBody EduVideo eduVideo){
        boolean flag = eduVideoService.updateById(eduVideo);
        if (flag){
            return R.ok();
        }else {
            return R.error();
        }
    }
    //删除小节信息
    @DeleteMapping("/deleteVideoById/{videoId}")
    @ApiOperation(value = "删除章节信息接口")
    public R deleteVideoById(@PathVariable String videoId){
        //根据小节id获取视频id，调用方法实现视频删除
        EduVideo eduVideo = eduVideoService.getById(videoId);
        String videoSourceId = eduVideo.getVideoSourceId();
        //判断小节里面是否有视频id
        if(!StringUtils.isEmpty(videoSourceId)) {
            //根据视频id，远程调用实现视频删除
            R result = vodClient.removeAlyVideo(videoSourceId);
            if (result.getCode()==20001){
                throw new GuliException(20001,"删除视频失败.调用了熔断器。。");
            }

        }

        boolean flag = eduVideoService.removeById(videoId);
        if (flag){
            return R.ok();
        }else {
            return R.error();
        }
    }


}

